<?php

namespace common\models;

use app\models\AdminLog;
use common\utils\XCache;
use Yii;

/**
 * This is the model class for table "banner_item".
 *
 * @property string $id
 * @property string $banner_id
 * @property string $title
 * @property string $sort
 * @property string $url
 * @property string $src
 *
 * @property Banner $banner
 */
class BannerItem extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'banner_item';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['banner_id', 'title'], 'required'],
            [['banner_id', 'sort'], 'integer'],
            [['title'], 'string', 'max' => 64],
            ['url', 'string', 'max' => 255],
            [['url'], 'url', 'defaultScheme' => 'http'],
            [['src'], 'image', 'extensions' => 'jpeg, jpg, gif, png', 'maxSize' => 1 * 1024 * 1024],
            [['banner_id'], 'exist', 'skipOnError' => true, 'targetClass' => Banner::className(), 'targetAttribute' => ['banner_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'banner_id' => 'BannerID',
            'title' => '标题',
            'sort' => '排序',
            'url' => '链接',
            'src' => '图片地址',
        ];
    }

    public function attributeHints()
    {
        return ['sort' => '数值小的在前'];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getBanner()
    {
        return $this->hasOne(Banner::className(), ['id' => 'banner_id']);
    }

    public function behaviors()
    {
        $path = '/uploads/image/' . date('Ymd') . '/' . time() . '[[pk]].[[extension]]';
        return [
            [
                'class' => '\yiidreamteam\upload\ImageUploadBehavior',
                'attribute' => 'src',
                'filePath' => '@frontend/web' . $path,
                'fileUrl' => $path
            ],
        ];
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($_FILES[$this->formName()]['name']['src']) {
            $this->updateAll(['src' => $this->getImageFileUrl('src')], ['id' => $this->id]);
        }
        if ($insert) {
            AdminLog::log("新添幻灯片图片：" . $this->title, "create");
        } else {
            @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $changedAttributes['src']));
            AdminLog::log("更新幻灯片图片：旧：" . $changedAttributes['title'] . "；新：" . $this->title);
        }
        $this->deleteCache();
    }

    public function afterDelete()
    {
        parent::afterDelete();
        @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $this->src));
        AdminLog::log("删除幻灯片图片：" . $this->title, "delete");
        $this->deleteCache();
    }

    private function deleteCache()
    {
        $banner = Banner::findOne($this->banner_id);
        if ($banner) {
            XCache::bannerDelete($banner->name);
        }
    }
}
